package no.runeway;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.bind.JAXBException;

import no.runeway.logentry.LogEntryParser;
import no.runeway.logentry.LogEntryParserImpl;
import no.runeway.logentry.LogFile;

/**
 * @author rune.forberg Parse file with NCSA extended/combined log format and
 *         return XML
 * */

public class ConvertLogFileToXml {

	/**
	 * @author rune.forberg@runeway.no
	 * @param String
	 * Takes one string only, which should be the file-path to a
	 * log file in NCSA extended/combined log format.
	 * 
	 * @throws IllegalArgumentException, JAXBException, FileNotFoundException, IOException
	 * */
	public final static void main(final String args[])
			throws IllegalArgumentException, FileNotFoundException,
			IOException, JAXBException {
		
		LogEntryParser logEntryParser = new LogEntryParserImpl();
		
		printHelpAndThrowExceptionIfWrongNumberOfArguments(args);
		
		LogFile logFile = new LogFile(
				logEntryParser.getLogEntriesFromBufferedReader(
						new BufferedReader(new FileReader(args[0]))));
		
		JAXBMarshaller.outputValidXmlObjectToXmlFile(logFile, args[0]+".xml");
	}

	private final static void printHelpAndThrowExceptionIfWrongNumberOfArguments(
			final String[] args) {
		if (args.length < 1) {
			System.out.println("Too few arguments. Usage 'java -jar "
					+ "ConvertLogFileToXml.jar [eksempel.log]'");
			throw new IllegalArgumentException();
		} else if (args.length > 1) {
			System.out.println("Too many arguments. Usage 'java -jar "
					+ "ConvertLogFileToXml.jar [eksempel.log]'");
			throw new IllegalArgumentException();
		}
	}

}
